﻿using EONFULLSIN2.Core.Extensions;
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace EONFULLSIN2.Services.DB
{
    public class DbOperate<DbContext>: IDbOperate<DbContext> where DbContext : IFreeSqlContext
    {
        private IFreeSql _dbContext;

        public DbOperate(DbContext dbContext)
        {
            _dbContext = dbContext.DbContext;
        }

        public bool AddModel<T>(T model) where T : class, new()
        {
            return _dbContext.Insert(model).ExecuteAffrows() > 0;
        }

        public bool AddModels<T>(List<T> models) where T : class, new()
        {
            return _dbContext.Insert(models).ExecuteAffrows() > 0;
        }

        public bool DeleteModel<T>(Expression<Func<T, bool>> exp) where T : class, new()
        {
            var sql = _dbContext.Delete<T>().Where(exp).ToSql();
            return _dbContext.Delete<T>().Where(exp).ExecuteAffrows() > 0;
        }

        public T GetModel<T>(Expression<Func<T, bool>> exp) where T : class, new()
        {
            return _dbContext.Select<T>().Where(exp).ToOne();
        }

        public List<T> GetModelList<T>(Expression<Func<T, bool>> exp) where T : class, new()
        {
            var str = _dbContext.Select<T>().Where(exp).ToSql();
            return _dbContext.Select<T>().Where(exp).ToList();
        }

        public bool UpdateModel<T>(Expression<Func<T, bool>> exp, Expression<Func<T, T>> exp2) where T : class, new()
        {
            var str = _dbContext.Update<T>().Set(exp2).Where(exp).ToSql();
            return _dbContext.Update<T>().Set(exp2).Where(exp).ExecuteAffrows() > 0;
        }

        public bool CheckExist<T>(Expression<Func<T, bool>> exp) where T : class, new()
        {
            var str = _dbContext.Select<T>().Where(exp).ToSql();
            return _dbContext.Select<T>().Any(exp);
        }

        public bool UpdateModelSuper<T>(Expression<Func<T, bool>> exp, T t) where T : class, new()
        {
            var str = _dbContext.Update<T>().SetSource(t).Where(exp).ToSql();
            return _dbContext.Update<T>().SetSource(t).Where(exp).ExecuteAffrows() > 0;
        }

        public bool ExceSql(string sql)
        {
            return _dbContext.Ado.ExecuteNonQuery(sql) > 0;
        }

        public List<T> ExceSqlToList<T>(string sql) where T : class, new()
        {
            return _dbContext.Ado.ExecuteDataTable(sql).ToList<T>();
        }

        public IFreeSql GetFreeSql() {
            return _dbContext;
        }
    }
}
